package com.eightbears.beboy.ui.merchant.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.widget.ImageView;
import android.widget.TextView;

import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.ShopSelDataAdapter;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.util.CommonUtils;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.ChartView;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.entity.ShopRunDataEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.socks.library.KLog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.URL_SHOPRUNDATA;


/**
 * 经营数据页面
 */
public class ShopRunDataActivity extends BaseActivity {

    //x轴坐标对应的数据
    private List<String> xValue = new ArrayList<>();
    //y轴坐标对应的数据
    private List<Integer> yValue = new ArrayList<>();
    //折线对应的数据
    private Map<String, Integer> value = new HashMap<>();
    private List<String> balanceValue = new ArrayList<>();

    private List<ShopRunDataEntity.DataBean.OnDateBean> mOn_date;

    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_run_sell)
    TextView tv_run_sell;
    @BindView(R.id.tv_run_consume)
    TextView tv_run_consume;
    @BindView(R.id.tv_run_date)
    TextView tv_run_date;
    @BindView(R.id.tv_run_balance)
    TextView tv_run_balance;
    @BindView(R.id.tv_run_num)
    TextView tv_run_num;
    @BindView(R.id.tv_run_consumption)
    TextView tv_run_consumption;
    @BindView(R.id.tv_run_sales)
    TextView tv_run_sales;
    @BindView(R.id.tv_runback_meal)
    TextView tv_runback_meal;
    @BindView(R.id.item_runback_balance)
    TextView item_runback_balance;
    @BindView(R.id.tv_run_calender)
    ImageView tv_run_calender;
    @BindView(R.id.sw_shopdetail)
    SwipeBackLayout sw;
    @BindView(R.id.rv_run)
    RecyclerView rv_run;
    @BindView(R.id.chartview)
    ChartView chartView;

    private String startTime;
    private String endTime;
    private ShopSelDataAdapter mShopRunDataAdapter;
    // private TimePickerView mTimePickerView;
    private int maxValue = 0;
    private int dataStatue = 3;

    //经营数据状态销售量和消费量切换状态
    public static int SHOPRUNSTATE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_run_data);
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
//        tv_run_date.setText("");
//        mTimePickerView = new TimePickerView(mContext, TimePickerView.Type.YEAR_MONTH);
//        tv_title.setText("经营数据");
//        tv_run_sales.setTextColor(Color.parseColor("#4d7aad"));
//        rv_run.setLayoutManager(new LinearLayoutManager(this));
//        Calendar calendar = Calendar.getInstance();
//        tv_run_date.setText(calendar.get(Calendar.YEAR) + "/" + (calendar.get(Calendar.MONTH) + 1));
//        chartView.setSelectDate(dataStatue);
    }

    @Override
    protected void initData() {
        mShopRunDataAdapter = new ShopSelDataAdapter();
        //获取当前月时间戳()
        startTime = CommonUtils.getStartTimeOfMonth();
        endTime = CommonUtils.getEndTimeOfMonth();
        //默认当前月的消费量（日）
        getShopRunData(String.valueOf(SHOPRUNSTATE), String.valueOf(1));
    }

    @Override
    protected void initEvent() {
        sw.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });
//
//        mTimePickerView.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {
//            @Override
//            public void onTimeSelect(Date date) {
//                String year = Integer.parseInt(DateUtil.timeYear(date.getTime() / 1000 + "")) - 1 + "";
//                //整年
//                if (year.equals(2017 + "")) {
//                    dataStatue = 1;
//                    startTime = DateUtil.dataShopRun(year + "年01月1日00时00分00");
//                    endTime = DateUtil.dataShopRun(year + "年12月31日23时59分59");
//                    getShopRunData(String.valueOf(SHOPRUNSTATE), String.valueOf(2));
//                    chartView.setSelectDate(dataStatue);
//                } else if (year.equals(2018)) {
//                    dataStatue = 1;
//                    startTime = DateUtil.dataShopRun(year + "年01月1日00时00分00");
//                    endTime = DateUtil.dataShopRun(year + "年12月31日23时59分59");
//                    getShopRunData(String.valueOf(SHOPRUNSTATE), String.valueOf(2));
//                    chartView.setSelectDate(dataStatue);
//                } else {//月
//                    dataStatue = 3;
//                    startTime = date.getTime() / 1000 + "";
//                    endTime = DateUtil.dataShopRun(DateUtil.timeY(date.getTime() / 1000 + "") + "31日11时59分59");
//                    getShopRunData(String.valueOf(SHOPRUNSTATE), String.valueOf(1));
//                    chartView.setSelectDate(dataStatue);
//                }
//            }
//        });
//
//        chartView.setOnItemClickListener(new ChartView.ChartClickListener() {
//            @Override
//            public void onChartClickListener(int position) {
//                ShopRunDataEntity.DataBean.OnDateBean onDateBean = mOn_date.get(position);
//                //mShopRunDataAdapter.setNewData(onDateBean.getEach_coupon());
//            }
//        });
    }

    @OnClick(R.id.ll_back)
    void back() {
        finish();
    }

    /**
     * 点击日历
     */
    @OnClick(R.id.tv_run_calender)
    void openCarlend() {
        //mTimePickerView.show();
    }

    /**
     * 消费量
     */
    @OnClick(R.id.tv_run_consumption)
    void consumption() {
        SHOPRUNSTATE = 2;
        tv_run_consumption.setTextColor(Color.parseColor("#4d7aad"));
        tv_run_sales.setTextColor(Color.parseColor("#4c4c4c"));
        getShopRunData(String.valueOf(SHOPRUNSTATE), String.valueOf(1));
    }

    /**
     * 销售量
     */
    @OnClick(R.id.tv_run_sales)
    void sales() {
        SHOPRUNSTATE = 1;
        tv_run_sales.setTextColor(Color.parseColor("#4d7aad"));
        tv_run_consumption.setTextColor(Color.parseColor("#4c4c4c"));
        getShopRunData(String.valueOf(SHOPRUNSTATE), String.valueOf(1));
    }

    /**
     * 通过网络获取当天验证记录数据
     */
    private void getShopRunData(String type, String date_type) {
        xValue.clear();
        yValue.clear();
        value.clear();
        String url = URL_SHOPRUNDATA + SPUtil.getUser().getData().getShops().get(0).getShop_id() + "" + "/businessData/";
        OkHttpUtils.get().url(url)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("start_at", startTime)
                .addParams("end_at", endTime)
                .addParams("type", type)
                .addParams("date_type", date_type)
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                KLog.e(response);
                ShopRunDataEntity shopRunDataEntity = GsonUtil.fromJson(response, ShopRunDataEntity.class);
                if (String.valueOf(shopRunDataEntity.getStatus_code()).equals(CONNECTION_STATUS_SUCCESS)) {
                    ShopRunDataEntity.DataBean data = shopRunDataEntity.getData();
                    tv_run_sell.setText(data.getTotal_purchases() + "");// 套餐总销售量
                    tv_run_consume.setText(data.getTotal_verify_purchases() + "");//套餐总消费量
                    tv_run_num.setText("+ " + data.getTotal_purchases() + "");//总的销售量
                    tv_run_balance.setText(data.getTotal_balance() + "");//总的销售金额

                    //每天数据
                    mOn_date = data.getOn_date();
                    KLog.e(mOn_date);
                    if (mOn_date.size() > 0) {
                        //设置chartview数据
                        for (int i = 0; i < data.getOn_date().size(); i++) {
                            if (data.getOn_date().get(i).getDate().length() < 8) {
                                xValue.add(data.getOn_date().get(i).getDate().substring(5));//设置X轴数据
                                value.put((data.getOn_date().get(i).getDate().substring(5)), data.getOn_date().get(i).getNum());
                            } else {
                                xValue.add(data.getOn_date().get(i).getDate().substring(8));//设置X轴数据
                                value.put((data.getOn_date().get(i).getDate().substring(8)), data.getOn_date().get(i).getNum());
                            }
                            KLog.e((data.getOn_date().get(i).getNum() + " --- num"));
                            //获取Y轴最大值
                            if (data.getOn_date().get(i).getNum() > maxValue) {
                                maxValue = data.getOn_date().get(i).getNum();
                            }
                            balanceValue.add(data.getOn_date().get(i).getBalance());
                        }
                        KLog.e(maxValue);
//                        if (data.getOn_date().size() < 5) {
                        //设置Y轴刻度值
                        if (maxValue >= 0 && maxValue <= 20) {
                            for (int i = 0; i < 5; i++) {
                                yValue.add(i * 5);
                            }
                        } else {
                            //设置Y轴刻度值
                            for (int i = 0; i < 5; i++) {
                                yValue.add(i * 20);
                            }
                        }

                    } else {
                        //没有数据


                    }
                    rv_run.setAdapter(mShopRunDataAdapter);
                    chartView.setValue(value, xValue, yValue);
//                    chartView.setBalance(balanceValue);
                    chartView.setSelectIndex(1);
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(ShopRunDataActivity.this, status_error);
            }
        });
    }
}
